<template>
  <section>
    <Spin fix size="large" v-if="loading1"/>
    <card v-if="$store.state.superAdmin == 'true'" style="margin-bottom: 10px">
      <el-select
        style="width: 100%"
        v-model="museumId"
        @change="change"
        filterable
        placeholder="请选择博物馆">
        <el-option
          v-for="item in museumList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </card>
    <el-row>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="title">预约统计</span>
          <div style="float: right">
            <el-date-picker
              v-model="time"
              type="daterange"
              align="right"
              unlink-panels
              size="small"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </div>
        <el-row>
          <el-col :span="12">
            <div class="tu">
              <div id="bing"></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="tu">
              <div id="zhe"></div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-row>
    <el-row style="margin-top: 10px" :gutter="10">
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span class="title">活动统计</span>
            <div style="float: right">
              <el-date-picker
                v-model="time1"
                type="daterange"
                align="right"
                unlink-panels
                size="small"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </div>
          <div class="tu">
            <div id="huo" v-if="ishuo"></div>
            <el-empty description="暂无活动"></el-empty>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span class="title">导览统计</span>
            <div style="float: right">
              <el-date-picker
                v-model="time2"
                type="daterange"
                align="right"
                unlink-panels
                size="small"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </div>
          <div class="tu">
            <div id="dao"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </section>
</template>

<script>
  import * as echarts from 'echarts'
  function getXmonthToday(type) {
    // type 0 是当天 -1 是上个月   1是下个月
    var now = new Date(); // 可以传值调式 now = new Date(2019,2,30); 今天是3月30号
    var year = now.getFullYear();//getYear()+1900=getFullYear()
    var month = now.getMonth() + 1;//0-11表示1-12月
    var day = now.getDate(); // 当天日期
    if (parseInt(month) < 10) {
      month = "0" + month;
    }
    if (parseInt(day) < 10) {
      day = "0" + day;
    }
    now = year + '-' + month + '-' + day; // 如果取当月日期可直接 return 返回

    var preMonth = parseInt(month)  - 1;
    preMonth = preMonth < 10 ? '0' + preMonth : preMonth; // 获取上个月的值
    var nextMonth = parseInt(month) + 1;
    nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth; // 获取下个月个月的值

    if (parseInt(month) == 1 && type == -1) {//如果是1月份，要上个月 ，则取上一年的12月份
      return (parseInt(year) - 1) + '-12-' + day;
    } else if (parseInt(month) == 12 && type == 1) { // 如果是12月，要下个月，取下一年的1月
      return (parseInt(year) + 1) + '-01-' + day;
    }

    var preSize  = new Date(year, parseInt(month) - 1, 0).getDate();//上月总天数
    var nextSize = new Date(year, parseInt(month)+ 1, 0).getDate();//下月总天数
    console.log(preSize, nextSize)
    if (preSize < parseInt(day) && type == -1) {// 取上个月，如果上个月总天数小于本月今天，取上个月最后一天
      return year + '-' + preMonth + '-' + preSize;
    } else if (nextSize < parseInt(day) && type == 1) { // 如果下个月总天数小于本月今天，取下个月最后一天
      return year + '-' + nextMonth + '-' + nextSize;
    }

    if (type == -1) {
      return year + '-' + preMonth + '-' + day;
    } else if (type == 1) {
      return year + '-' + nextMonth + '-' + day;
    }else if(type == 0){
      return now;
    }
  };
  let currentDate = new Date();
  let shangYue = new Date(getXmonthToday(-1));
  let time = [shangYue, currentDate];
  let time1 = [shangYue, currentDate];
  let time2 = [shangYue, currentDate];
  export default {
    name: 'accessStatistics',
    data () {
      return {
        museumId: "",
        museumList: [],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        time,
        time1,
        time2,
        bing: {},
        zhe: {},
        huo: {},
        dao: {},
        resize: null,
        ishuo: true
      }
    },
    watch: {
      time: {
        handler() {
          let currentDate = this.getTime(this.time[1]);
          let shangYue = this.getTime(this.time[0]);
          this.qushi(shangYue, currentDate);
        }
      },
      time1: {
        handler() {
          let currentDate = this.getTime(this.time1[1]);
          let shangYue = this.getTime(this.time1[0]);
          this.huodong(shangYue, currentDate);
        }
      },
      time2: {
        handler() {
          let currentDate = this.getTime(this.time2[1]);
          let shangYue = this.getTime(this.time2[0]);
          this.daolan(shangYue, currentDate);
        }
      },
      museumId() {
        this.initCharts();
      }
    },
    created () {
      // 监听图表
      this.resize = () => {
        this.bing.resize();
        this.zhe.resize();
        this.huo.resize();
        this.dao.resize();
      }
      window.addEventListener('resize', this.resize)
      if (this.$store.state.superAdmin === "true") {
        this.getmuseumList(() => {
          this.initCharts();
        });
      } else {
        if (this.$store.state.museums.length > 1) {
          this.museumId = parseInt(this.$store.state.museumId);
        } else {
          this.museumId = "";
        }
      }
    },
    mounted () {
      this.initCharts();
    },
    methods: {
      initCharts() {
        let currentDate = this.getTime(this.time[1]);
        let shangYue = this.getTime(this.time[0]);
        this.qushi(shangYue, currentDate);
        this.huodong(shangYue, currentDate);
        this.daolan(shangYue, currentDate);
        this.jinri();
      },
      change(e) {
        this.museumId = e;
      },
      // 获取场馆信息哦
      getmuseumList(fn) {
        this.loading1 = true;
        this.$http("/stage/museum/getAppMuseumDropDown", {}, "post", (res) => {
          if (res.data.code == 200) {
            this.museumList = res.data.data;
            for (let i = 0; i < this.museumList.length; i++) {
              if (this.museumList[i].name.length > 50) {
                this.museumList[i].name =
                  this.museumList[i].name.slice(0, 50) + "...";
              }
            }
            this.loading1 = false;
            this.museumId = this.museumList[0].id;
            fn && fn();
          } else {
            this.$Message.error(res.data.msg);
          }
        });
      },
      daolan (beginDate, endDate) {
        this.$http('/stage/access/getAudioPlayUv', {
          beginDate,
          endDate,
          museumId: this.museumId
        }, 'post', (res) => {
          let xData = []
          let yData = []
          res.data.data.forEach(item => {
            xData.push(item.date)
            yData.push(item.uv)
          })
          this.initZhu2(xData, yData)
        })
      },
      huodong (beginDate, endDate) {
        this.$http('/stage/access/getActivityUv', {
          beginDate,
          endDate,
          museumId: this.museumId
        }, 'post', (res) => {
          this.ishuo = res.data.data.length
          let xData = []
          let yData = []
          let yData2 = []
          res.data.data.forEach(item => {
            xData.push(item.name)
            yData.push(item.limitNum)
            yData2.push(item.num)
          })
          if(!xData.length && !yData2.length && !yData.length) {
            this.ishuo = false;
          } else {
            this.ishuo = true;
            this.$nextTick(() => {
              this.initZhu(xData, yData, yData2)
            })
          }
        })
      },
      qushi (beginDate, endDate) {
        this.$http('/stage/access/getBookPeopleUv', {
          beginDate,
          endDate,
          museumId: this.museumId
        }, 'post', (res) => {
          let xData = []
          let yData = []
          res.data.data.forEach(item => {
            xData.push(item.date)
            yData.push(item.uv)
          })
          this.initZhe(xData, yData)
        })
      },
      jinri() {
        this.$http('/stage/access/getTodayBookUv', {museumId: this.museumId}, 'post', res => {
          let data = [
            { name: '核销人数', value: res.data.data.usedNum  },
            { name: '预约人数', value: res.data.data.bookNum  }

          ]
          this.initBing(data);
        })
      },
      initBing (data) {
        let option = {
          title: {
            text: '今日概览',
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'horizontal',
            left: 'center',
          },
          series: [
            {
              color: ['rgb(80,135,236)', 'rgb(114,205,215)'],
              hoverAnimation: false,
              type: 'pie',
              radius: '70%',

              data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        this.bing = echarts.init(document.getElementById('bing'))
        option && this.bing.setOption(option)
      },
      initZhe (x, y) {
        let option = {
          color: '#3398DB',
          title: {
            text: '预约人数趋势',
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
              shadowStyle: {
                shadowColor: 'rgba(0, 165, 220, 0.5)',
                shadowBlur: 10
              }
            }
          },
          xAxis: {
            type: 'category',
            data: x
          },
          yAxis: {
            type: 'value',
            axisTick: {       //y轴刻度线
              'show': false
            },
            axisLine: {       //y轴
              'show': false
            },
          },
          series: [
            {
              data: y,
              type: 'line'
            },
          ]
        }
        this.zhe = echarts.init(document.getElementById('zhe'))
        option && this.zhe.setOption(option)
      },
      //活动
      initZhu (x, y, y1) {
        let option = {
          color: ['#3398DB', 'rgb(104,187,196)'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: x
            }
          ],
          yAxis: [
            {
              type: 'value',
              axisTick: {       //y轴刻度线
                'show': false
              },
              axisLine: {       //y轴
                'show': false
              },
            }
          ],
          series: [
            {
              name: '限制人数',
              barGap: 0,
              barMaxWidth: 30,
              type: 'bar',
              data: y
            },
            {
              name: '报名人数',
              barMaxWidth: 30,
              type: 'bar',
              data: y1
            }
          ]
        }
        this.huo = echarts.init(document.getElementById('huo'))
        option && this.huo.setOption(option)
      },
      // 导览数据
      initZhu2 (x, y) {
        let option = {
          color: ['#3398DB'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: x
            }
          ],
          yAxis: [
            {
              type: 'value',
              axisTick: {       //y轴刻度线
                'show': false
              },
              axisLine: {       //y轴
                'show': false
              },
            }
          ],
          series: [
            {
              type: 'bar',
              data: y,
              barMaxWidth: 30,
            }
          ]
        }
        this.dao = echarts.init(document.getElementById('dao'))
        option && this.dao.setOption(option)
      }
    },
    destroyed () {
      window.removeEventListener('resize', this.resize);
    }
  }
</script>

<style scoped lang="less">
  .title {
    font-size: 18px;
    font-weight: bold;
  }

  .tu {
    height: 350px;

    div {
      width: 100%;
      height: 100%;
    }
  }
</style>
